package org.dromara.web.thread;

import lombok.extern.slf4j.Slf4j;
import org.dromara.web.modbus.service.ModbusService;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
@Slf4j
public class ThreadServer implements Runnable {

    private final ModbusService modbusService;

    public ThreadServer(ModbusService modbusService) {
        this.modbusService = modbusService;

    }

    @Override
    public void run() {
        log.info("启动 Modbus 数据读取线程...");

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        Runnable task = () -> {
            int batchSize = 150; // 每批次读取量减小以提高效率
            int threadCount = 20; // 增加线程池大小提高并发性能

            ExecutorService executor = Executors.newFixedThreadPool(threadCount);
            try {
                executor.submit(() -> modbusService.batchReadConcurrently(batchSize, threadCount)).get();
            } catch (Exception e) {
                log.error("读取任务执行失败: {}", e.getMessage(), e);
            } finally {
                executor.shutdown();
            }
        };

        // 每2分钟执行一次任务
        scheduler.scheduleAtFixedRate(task, 0, 40, TimeUnit.SECONDS);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("关闭调度器...");
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }));

    }
}
